using System;
using System.Net;
using System.Collections;
using System.Text;
using System.IO;
using System.Configuration;
using System.Collections.Generic;

/**
 *  AOA(c) 2008, licensed 'AS IS'
 * 
 *  Library for HTTP service localizame from Movistar
 * 
 **/

namespace aoa.csharp.pc.DondeEstas.localizame
{
    public class DondeEstas
    {
        //constants
        private static string LOGIN_URL = ConfigurationManager.AppSettings["LOGIN_URL"].ToString();
        private static string LOGOUT_URL = ConfigurationManager.AppSettings["LOGOUT_URL"].ToString();
        private static string NEW_USER_URL = ConfigurationManager.AppSettings["NEW_USER_URL"].ToString();
        private static string LOCALIZA_URL = ConfigurationManager.AppSettings["LOCALIZA_URL"].ToString();
        private static string AUTORIZA_URL = ConfigurationManager.AppSettings["AUTORIZA_URL"].ToString();
        private static string DESAUTORIZA_URL = ConfigurationManager.AppSettings["DESAUTORIZA_URL"].ToString();

        //global variables
        private System.Net.CookieContainer cookieContainer = new CookieContainer();

        #region login
        //login method
        public bool login(string userName, string password)
        {
            try
            {
                ////Call to LOGIN
                //format query for post
                string query = String.Format("usuario=%s&clave=%s&submit.x=36&submit.y=6", userName, password);
                //adittional headers
                List<MyHttpRequestHeader> list = new List<MyHttpRequestHeader>();
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptLanguage, "es"));
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptEncoding, "identity"));
                //call login
                WebResponse response = httpPost(LOGIN_URL, "application/x-www-form-urlencoded", list.ToArray(), query, "");

                ////Call to NEW USER
                response = httpGet(NEW_USER_URL, "application/x-www-form-urlencoded", list.ToArray(), query, LOGIN_URL);


            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }
        #endregion

        #region logout
        //logout method
        public bool logout(string userName, string password)
        {
            try
            {
                ////Call to LOGOUT
                //format query for post
                string query = "";
                //adittional headers
                List<MyHttpRequestHeader> list = new List<MyHttpRequestHeader>();
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptLanguage, "es"));
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptEncoding, "identity"));
                //call logout
                WebResponse response = httpGet(LOGOUT_URL, "application/x-www-form-urlencoded", list.ToArray(), query, "");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }
        #endregion

        #region localiza
        //localiza method
        public string localiza(string number)
        {
            try
            {
                ////Call to LOCALIZA
                //format query for post
                string query = String.Format("telefono=%s", number);
                //adittional headers
                List<MyHttpRequestHeader> list = new List<MyHttpRequestHeader>();
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptLanguage, "es"));
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptEncoding, "identity"));
                //call localiza
                WebResponse response = httpPost(LOCALIZA_URL, "application/x-www-form-urlencoded", list.ToArray(), query, "");
                //read data
                StreamReader sw = new StreamReader(response.GetResponseStream());
                string data = sw.ReadToEnd();
                //return data
                return data;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region autoriza
        //autoriza method
        public string autoriza(string number)
        {
            try
            {
                ////Call to AUTORIZA
                //format query for post
                string query = String.Format("telefono=%s&submit.x=40&submit.y=5", number);
                //adittional headers
                List<MyHttpRequestHeader> list = new List<MyHttpRequestHeader>();
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptLanguage, "es"));
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptEncoding, "identity"));
                //call localiza
                WebResponse response = httpGet(AUTORIZA_URL, "application/x-www-form-urlencoded", list.ToArray(), query, "http://www.localizame.movistar.es/buscalocalizadorespermisos.do\r\n");
                //read data
                StreamReader sw = new StreamReader(response.GetResponseStream());
                string data = sw.ReadToEnd();
                //return data
                return data;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region desautoriza
        //desautoriza method
        public string desautoriza(string number)
        {
            try
            {
                ////Call to DESAUTORIZA
                //format query for post
                string query = String.Format("telefono=%s&submit.x=44&submit.y=8", number);
                //adittional headers
                List<MyHttpRequestHeader> list = new List<MyHttpRequestHeader>();
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptLanguage, "es"));
                list.Add(new MyHttpRequestHeader(HttpRequestHeader.AcceptEncoding, "identity"));
                //call localiza
                WebResponse response = httpGet(DESAUTORIZA_URL, "application/x-www-form-urlencoded", list.ToArray(), query, "http://www.localizame.movistar.es/buscalocalizadorespermisos.do\r\n");
                //read data
                StreamReader sw = new StreamReader(response.GetResponseStream());
                string data = sw.ReadToEnd();
                //return data
                return data;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region httpPost
        //HTTP Post method
        public WebResponse httpPost(string url, string contentType, MyHttpRequestHeader[] headers, string query, string referer)
        {
            WebResponse response = null;
            try
            {
                //create request
                WebRequest request = WebRequest.Create(url);
                request.UseDefaultCredentials = true;
                //set contentType
                request.ContentType = contentType; // "Content-type: application/x-www-form-urlencoded\r\n";
                //no credentials
                request.Credentials = CredentialCache.DefaultCredentials;
                //Accept header
                ((HttpWebRequest)request).Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
                //set method
                request.Method = "POST";
                //set headers
                foreach (MyHttpRequestHeader header in headers)
                {
                    request.Headers.Add(header.HttpRequestHeader, header.Value);
                }
                //referer
                if (referer != null)
                {
                    if (referer.Length > 0)
                        ((HttpWebRequest)request).Referer = referer;
                }
                //encoding related code: ASCII
                ASCIIEncoding encoding = new ASCIIEncoding();
                //get data bytes for ASCII
                byte[] data;
                data = encoding.GetBytes(query);
                //set contentLength
                request.ContentLength = data.Length;
                //write data bytes in request
                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();
                //create the cookie container
//                ((HttpWebRequest)request).CookieContainer = new CookieContainer();
                ((HttpWebRequest)request).CookieContainer = this.cookieContainer;

                //call
                response = request.GetResponse();
                //assign the cookies
//                ((HttpWebResponse)response).Cookies = ((HttpWebRequest)request).CookieContainer.GetCookies(request.RequestUri);
                this.cookieContainer = ((HttpWebRequest)request).CookieContainer;
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return response;
        }
        #endregion

        #region httpGet
        //HTTP Get method
        public WebResponse httpGet(string url, string contentType, MyHttpRequestHeader[] headers, string query, string referer)
        {
            WebResponse response = null;
            try
            {
                //create request
                WebRequest request = WebRequest.Create(url + "?" + query);
                //default credentials
                request.UseDefaultCredentials = true;
                //set contentType
                request.ContentType = contentType; // "Content-type: application/x-www-form-urlencoded\r\n";
                //no credentials
                request.Credentials = CredentialCache.DefaultCredentials;
                //Accept header
                ((HttpWebRequest)request).Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
                //set method
                request.Method = "GET";
                //set headers
                foreach (MyHttpRequestHeader header in headers)
                {
                    request.Headers.Add(header.HttpRequestHeader, header.Value);
                }
                //referer
                if (referer != null)
                {
                    if (referer.Length > 0)
                        ((HttpWebRequest)request).Referer = referer;
                }
                //create the cookie container
//                ((HttpWebRequest)request).CookieContainer = new CookieContainer();
                ((HttpWebRequest)request).CookieContainer = this.cookieContainer;

                //call
                response = request.GetResponse();
                //assign the cookies
//                ((HttpWebResponse)response).Cookies = ((HttpWebRequest)request).CookieContainer.GetCookies(request.RequestUri);
                this.cookieContainer = ((HttpWebRequest)request).CookieContainer;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return response;
        }
        #endregion

    }

    #region MyHttpRequestHeader
    public class MyHttpRequestHeader
    {
        private HttpRequestHeader httpRequestHeader;
        private string value;

        public HttpRequestHeader HttpRequestHeader
        {
            get { return httpRequestHeader; }
            private set { httpRequestHeader = value; }
        }

        public string Value
        {
            get { return this.value; }
            private set { this.value = value; }
        }

        public MyHttpRequestHeader(HttpRequestHeader header, string value)
        {
            this.HttpRequestHeader = header;
            this.Value = value;
        }

    }
    #endregion

}
